package vivace.view;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.sound.midi.MidiEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;

import vivace.helper.GUIHelper;
import vivace.model.App;

public class EventEditFrame extends JFrame {
	
	private static final long serialVersionUID = 8899458377934771848L;
	SpinnerNumberModel spinnerModel;
	MidiEvent event;
	
	EventEditFrame frame;
	
	/**
	 * Constructor
	 * @param event
	 */
	public EventEditFrame(MidiEvent event) {
		this.event = event;
		frame = this;
		
		setTitle("Event");
		setPreferredSize(new Dimension(200, 200));
		setLocationRelativeTo(null);
		setResizable(false);
		setAlwaysOnTop(true);
		setIconImage(GUIHelper.icon);
		
		Container c = getContentPane();
		c.setLayout(new BorderLayout());
		
		spinnerModel =
	        new SpinnerNumberModel();
		spinnerModel.setValue(new Long(event.getTick()));
		spinnerModel.setMinimum(new Long(0));
		spinnerModel.setStepSize(new Long(1));

		JSpinner tickSpinner = new JSpinner(spinnerModel);
		tickSpinner.setPreferredSize(new Dimension(100, 25));
		
		JPanel p = new JPanel();
		p.add(new JLabel("Tick: "));
		p.add(tickSpinner);
		
		c.add(p, BorderLayout.CENTER);
		
		JButton okButton = new JButton("OK");
		okButton.setActionCommand("ok");
		okButton.addActionListener(new Controller());
		
		c.add(okButton, BorderLayout.SOUTH);
		
		pack();
	}
	
	private class Controller implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			String cmd = e.getActionCommand();
			
			if (cmd.equals("ok")) {
				long tick = spinnerModel.getNumber().longValue();
				
				if (tick != event.getTick()) {
					System.out.println("Tick changed!");
					App.Project.moveEvent(event, tick, true);
					
					frame.setVisible(false);
					frame.dispose();
					
				}
			}
			
		}
		
	}
}
